<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket 测试</title>
</head>
<body>
<h1>WebSocket 测试客户端</h1>
<div>
    <input type="text" id="messageInput" placeholder="输入消息">
    <button onclick="sendMessage()">发送</button>
</div>
<div id="messages" style="margin-top: 20px; border: 1px solid #ccc; padding: 10px; height: 300px; overflow-y: scroll;">

</div>

<script>
    //Bom 包含了WebSocket
    const ws = new WebSocket('ws://localhost:3030');
    const messagesDiv = document.getElementById('messages');
    const messageInput = document.getElementById('messageInput');

    //协议连接打开
    ws.onopen = function(event) {
        addMessage('系统', '已连接到服务器');
    };

    ws.onmessage = function(event) {
        addMessage('服务器', event.data);
    };

    ws.onclose = function(event) {
        addMessage('系统', '连接已断开');
    };

    ws.onerror = function(error) {
        addMessage('错误', error);
    };


    //发送
    function sendMessage() {
        const message = JSON.stringify({
            type : 'chat',
            user : "徐艺涵",
            messsage : messageInput.value,
        })


        if (message) {
            ws.send(message);
            addMessage('我', message);
            messageInput.value = '';
        }
    }

    function addMessage(sender, message) {
        const messageElement = document.createElement('div');
        messageElement.innerHTML = `<strong>${sender}:</strong> ${message}`;
        messagesDiv.appendChild(messageElement);
        messagesDiv.scrollTop = messagesDiv.scrollHeight;
    }

    messageInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });
</script>
</body>
</html>